package studio.xiaoyun.file;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import studio.xiaoyun.core.Config;

import java.io.File;

/**
 * 定时删除临时文件
 */
@Service
public class DeleteTmpFileTask {
    private Logger logger = LoggerFactory.getLogger(DeleteTmpFileTask.class);
    /**
     * 删除临时文件
     */
    public void deleteTmpFile(){
        logger.info("开始删除临时文件");
        int fileAmount;
        File uploadFile = new File(Config.getUploadPath());
        File[] tmpFiles = uploadFile.listFiles();
        fileAmount = tmpFiles.length;
        for(File file:tmpFiles){
            deleteFile(file);
        }
        File converterFile = new File(Config.getConvertPath());
        tmpFiles = converterFile.listFiles();
        fileAmount += tmpFiles.length;
        for(File file:tmpFiles){
            deleteFile(file);
        }
        logger.info("删除临时文件完成,共删除了"+fileAmount+"个文件");
    }

    private void deleteFile(File file){
        if(file.isDirectory()){
            File[] files = file.listFiles();
            for(int i=0;files!=null&&i<files.length;i++){
                deleteFile(files[i]);
            }
            file.delete();
        }else{
            file.delete();
        }
    }
}
